import axios from 'axios'
import { ElMessage } from 'element-plus'
const instance = axios.create({
  baseURL: 'api',
  timeout: 50000
})

axios.interceptors.request.use(
  config => {
    let token = localStorage.getItem('token')
    if (token) config.headers['token'] = token
    return config
  },
  error => console.log('error' + error)
)

axios.interceptors.response.use(
  res => res,
  error => {
    if (error && error.response) {
      const status = error.response.status
      // switch判断状态码
      console.log(status)
    } else {
      if (JSON.stringify(error).includes('timeout')) {
        ElMessage.error('服务器响应超时，请刷新页面')
      }
      ElMessage.error('连接服务器失败')
    }
    return Promise.reject(error)
  }
)

export default instance
